
package guoan.service;

import guoan.Exception.RestException;
import guoan.core.common.WebConfig;
import guoan.domain.Keyword;
import guoan.domain.Menu;
import guoan.repository.MenuRepository;
import guoan.service.weixin.WeiXinService;

import java.util.List;

import org.jeewx.api.core.req.model.menu.WeixinButton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.gson.Gson;

@Service
@Transactional(readOnly = false)
public class MenuService extends PageSerivce<Menu> {
    protected final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private MenuRepository menuRepository;
    @Autowired
    private WeiXinService weiXinService;
    @Autowired
    private KeywordService keywordService;
    @Value("${weixin.host}")
    private String host;

    public List<Menu> findList(){
        // TODO Auto-generated method stub
        List<Menu> menus = Lists.newArrayList();
        List<Menu> rootMenus = findMenuByRootId(0L);
        for (Menu rootMenu : rootMenus) {
            menus.add(rootMenu);
            List<Menu> paentMenus = findMenuByRootId(rootMenu.getId());
            for (Menu paentMenu : paentMenus) {
                menus.add(paentMenu);
            }
        }
        return menus;
    }

    public List<Menu> findMenuByRootId(Long rootId){
        return menuRepository.findByRootIdOrderByOrderIdDesc(rootId);
    }

    @Transactional(readOnly = false, rollbackFor = { RestException.class })
    public Boolean update(Menu menu){
        // TODO Auto-generated method stub
        // 如果是父节点,那么只允许有三个menu
        menuRepository.save(menu);
        if (menu.getRootId() == 0L && findMenuCount(0L) == 4) {
            throw new RestException("只允许有三个一级菜单");
        }
        if (menu.getRootId() != 0L && findMenuCount(menu.getRootId()) == 6) {
            throw new RestException("每一个菜单只允许有五个二级菜单");
        }
        return true;
    }

    /**
     * @Title：findMenuCount
     * @Description: 每级menu个数
     * @author Hyman Sun
     * @date 2015年6月15日 上午10:49:57
     * @param rootId
     * @return
     */
    public Long findMenuCount(Long rootId){
        return menuRepository.countByRootId(rootId);
    }

    public Menu findOne(Long id){
        // TODO Auto-generated method stub
        return menuRepository.findOne(id);
    }

    public Boolean delete(Long id){
        // TODO Auto-generated method stub
        Menu menu = findOne(id);
        menuRepository.delete(menu);
        List<Menu> menus = findMenuByRootId(id);
        menuRepository.delete(menus);
        return true;
    }

    public Boolean push(){
        // TODO Auto-generated method stub
        List<WeixinButton> buttons = Lists.newArrayList();
        List<Menu> rootMenus = findMenuByRootId(0L);
        if (rootMenus.size() == 0) {
            throw new RestException("当前没有菜单");
        } else {
            for (Menu rootMenu : rootMenus) {
                WeixinButton button = formatWeixinButton(rootMenu);
                List<Menu> paentMenus = findMenuByRootId(rootMenu.getId());
                List<WeixinButton> paentButtons = Lists.newArrayList();
                for (Menu paentMenu : paentMenus) {
                    paentButtons.add(formatWeixinButton(paentMenu));
                }
                if (paentButtons.size() > 0) {
                    button.setType(null);
                    button.setKey(null);
                    button.setSub_button(paentButtons);
                }
                buttons.add(button);
            }
            System.out.println(new Gson().toJson(buttons));
            weiXinService.createMenu(buttons);
        }
        return true;
    }

    private WeixinButton formatWeixinButton(Menu menu){
        WeixinButton button = new WeixinButton();
        button.setName(menu.getKeyName());
        // 判断是否有关键字
        String link = null;
        if (!Strings.isNullOrEmpty(menu.getKeyName())) {
            Keyword keyword = keywordService.findTop1ByKeyName(menu
                    .getKeyName());
            if (keyword != null) {
                link = "http://"
                        + host
                        + WebConfig.findAppLink(keyword.getKeyInfo(),
                                keyword.getKeyInfoId());
            }
        }
        if (link == null && !Strings.isNullOrEmpty(menu.getwUrl())) {
            link = menu.getwUrl(); 
        }
        if (link == null) {
            button.setType("click");
            button.setKey(WebConfig.WEIXIN_MENU_NOKEY);
        } else {
            button.setType("view");
            button.setUrl(link);
        }
        button.setName(menu.getTitle());
        return button;
    }

}
